package com.naire.modul.customer.dao.impl;

import java.util.ArrayList;
import java.util.List;

import net.common.dao.GeneralDaoImpl;
import net.common.service.PageBean;
import net.common.util.BeanUtils;

import com.naire.modul.cusorg.pojo.Cusorg;
import com.naire.modul.customer.dao.CustomerDao;
import com.naire.modul.customer.pojo.Customer;
import com.naire.modul.customer.vo.CustomerVo;

public class CustomerDaoImpl extends GeneralDaoImpl implements CustomerDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<CustomerVo> search(PageBean pageBean) throws Exception {
		StringBuilder hql = new StringBuilder("from Customer where flag=0");
		List<CustomerVo> d = new ArrayList<CustomerVo>();
		List<Customer> l = hibernateHandler.query(hql, pageBean);
		for (Customer bean : l) {
			CustomerVo dv = new CustomerVo();
			BeanUtils.copyProperties(bean, dv);
			Cusorg c = bean.getCusorg();
			if (c != null) {
				dv.setOrg_name(c.getOrg_name());
			}
			d.add(dv);
		}
		return d;
	}

	@Override
	public void insert(CustomerVo bean) throws Exception {
		Customer pojo = new Customer();
		BeanUtils.copyProperties(bean, pojo);
		if (bean.getOrg_id() != null) {
			Cusorg c = (Cusorg) hibernateHandler.find(Cusorg.class,
					bean.getOrg_id());
			pojo.setCusorg(c);
		}
		hibernateHandler.insert(pojo);
	}

	@Override
	public void update(CustomerVo bean) throws Exception {
		Customer pojo = (Customer) hibernateHandler.find(Customer.class,
				bean.getCust_id());
		BeanUtils.copyProperties(bean, pojo);
		if (bean.getOrg_id() != null) {
			Cusorg c = (Cusorg) hibernateHandler.find(Cusorg.class,
					bean.getOrg_id());
			pojo.setCusorg(c);
		}
		hibernateHandler.update(pojo);
	}

	@Override
	public void updateFlag(CustomerVo bean) throws Exception {
		update(bean);
	}

	@Override
	public CustomerVo find(Integer id) throws Exception {
		Customer pojo = (Customer) hibernateHandler.find(Customer.class, id);
		CustomerVo bean = new CustomerVo();
		BeanUtils.copyProperties(pojo, bean);
		Cusorg c = pojo.getCusorg();
		if (c != null) {
			bean.setOrg_id(c.getOrg_id());
			bean.setOrg_name(c.getOrg_name());
		}
		return bean;
	}

	@Override
	public String findText(Integer id) throws Exception {
		Customer pojo = (Customer) hibernateHandler.find(Customer.class, id);
		return pojo.getCust_type();
	}
}
